package com.xgkj.diyiketang.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.sina.weibo.sdk.api.TextObject;
import com.sina.weibo.sdk.api.WebpageObject;
import com.sina.weibo.sdk.api.WeiboMultiMessage;
import com.sina.weibo.sdk.api.share.BaseResponse;
import com.sina.weibo.sdk.api.share.IWeiboHandler;
import com.sina.weibo.sdk.api.share.IWeiboShareAPI;
import com.sina.weibo.sdk.api.share.SendMultiMessageToWeiboRequest;
import com.sina.weibo.sdk.api.share.WeiboShareSDK;
import com.sina.weibo.sdk.auth.AuthInfo;
import com.sina.weibo.sdk.auth.Oauth2AccessToken;
import com.sina.weibo.sdk.auth.WeiboAuthListener;
import com.sina.weibo.sdk.constant.WBConstants;
import com.sina.weibo.sdk.exception.WeiboException;
import com.sina.weibo.sdk.utils.Utility;
import com.tencent.connect.share.QQShare;
import com.tencent.mm.sdk.modelmsg.SendMessageToWX;
import com.tencent.mm.sdk.modelmsg.WXMediaMessage;
import com.tencent.mm.sdk.modelmsg.WXWebpageObject;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.xgkj.diyiketang.EatShowApp;
import com.xgkj.diyiketang.ProtocolConst;
import com.xgkj.diyiketang.activity.data.PhotoAdapter;
import com.xgkj.diyiketang.data.PhotoInfo;
import com.xgkj.diyiketang.task.ChaKanXiangCeTask;
import com.xgkj.diyiketang.R;
import com.xgkj.diyiketang.activity.data.VideoAdapter;
import com.xgkj.diyiketang.data.EatShowUserInfo;
import com.xgkj.diyiketang.data.VideoInfo;
import com.xgkj.diyiketang.http.engine.ShowToastTaskEventListener;
import com.xgkj.diyiketang.http.engine.TaskEventListener;
import com.xgkj.diyiketang.task.AddOrCancleFocusTask;
import com.xgkj.diyiketang.task.GetOtherVideoListTask;
import com.xgkj.diyiketang.task.GetUserInfoTask;
import com.xgkj.diyiketang.task.TouPiaoTask;
import com.xgkj.diyiketang.util.AccessTokenKeeper;
import com.xgkj.diyiketang.util.ImageCache;
import com.xgkj.diyiketang.util.ToastUtil;
import com.xgkj.diyiketang.util.ViewUtil;
import com.xgkj.diyiketang.util.WeixinShareUtil;
import com.xgkj.diyiketang.weidget.MyScrollView;
import com.xgkj.diyiketang.weidget.NoScrollGridView;
import com.xgkj.diyiketang.weidget.RoundImageView;
import com.xgkj.diyiketang.wxapi.WXEntryActivity;


import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by windo on 2015/12/18.
 */
public class AnchorActivity extends BaseActivity implements MyScrollView.OnScrollListener, View.OnClickListener, IWeiboHandler.Response {

    private static final String TAG = AnchorActivity.class.getSimpleName();
    private static final String USERID = "userId";
    private Context mContext;
    private RoundImageView mHeadImg;
    private TextView fansNumText;
    private TextView attentionBtn;
//    private Button sendMsgBtn;
    private TextView mNickNameText;
    private TextView mPersonSignatureText;
    private MyScrollView mScrollView;
    private NoScrollGridView mVideoList;
    private VideoAdapter mAdapter;

    private NoScrollGridView photoGridView;
    private PhotoAdapter photeAdapter;
    private CheckBox mGuanZhuBtn;
    private CheckBox mPhotoBtn;
    // private LinearLayout mGuanzhuLayout;
    private LinearLayout mPhotoLayout;
    private int xiangceListTaskId = -1;
    private int currentPage_p =1;
    private String mUserId;
    private int mUserTaskId = -1;
    private int mVideoListTaskId = -1;
    private int focusTaskId = -1;
    private int cancleFocusTaskId = -1;
    private int size = 16;
    private int currentPage = 1;
    private EatShowUserInfo userInfo;
    private ImageView back;
    private TextView noMoreText;
    //private TextView mHisZuoPin;
    private LinearLayout chatLayout;
    private LinearLayout toupiaoLayout;
    private int tpTaskId = -1;
    private ImageView share;
    private PopupWindow popWindow;
    private String share_path;

    private WeixinShareReceive mWeixinShareReceive;
    private String weixinsharetype;
    private String weixinuseropenid;
    private String weibouserid;
    private Bitmap weiboShareBitmap;
    private byte[] weixinshareByte;
    private IWXAPI api;
    private IWeiboShareAPI mWeiboShareAPI = null;
    private String shoucangtype;
    public static Tencent mTencent;

    private String share_title;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.anchor);
        mContext = this;
        mTencent = Tencent.createInstance(ProtocolConst.QQ_ID, this.getApplicationContext());
        api = WXAPIFactory.createWXAPI(mContext, ProtocolConst.APP_ID);
//        mWeiboShareAPI = WeiboShareSDK.createWeiboAPI(this,
//                ProtocolConst.WEIBO_APP_KEY);//这粒要换
//        mWeiboShareAPI.registerApp();
//        if (savedInstanceState != null) {
//            mWeiboShareAPI.handleWeiboResponse(getIntent(), this);
//        }
        initView();
    }

    @Override
    protected void onNewIntent(Intent intent) {
        // TODO Auto-generated method stub
        super.onNewIntent(intent);
//        mWeiboShareAPI.handleWeiboResponse(intent, this);
    }

    public static Intent getIntent(Context context, String uid) {
        Intent intent = new Intent(context, AnchorActivity.class);
        intent.putExtra(USERID, uid);
        return intent;
    }

    private void initView() {
        Intent intent = getIntent();
        if (intent != null) {
            mUserId = intent.getStringExtra(USERID);
        }
        //PalLog.e("被投票的人的ID", mUserId);
        share_path = "http://www.chiboker.com:8096/liveshow/video_list.html?userid=" + mUserId + "";
        back = (ImageView) findViewById(R.id.back);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        back.setFocusable(true);
        back.setFocusableInTouchMode(true);
        back.requestFocus();

        noMoreText = (TextView) findViewById(R.id.no_more);
        //mHisZuoPin = (TextView) findViewById(R.id.hiszuopin);
        mHeadImg = (RoundImageView) findViewById(R.id.head_img);
        fansNumText = (TextView) findViewById(R.id.fans_num);
        fansNumText.setOnClickListener(this);
        attentionBtn = (TextView) findViewById(R.id.attention_btn);
        attentionBtn.setOnClickListener(this);
//        sendMsgBtn = (Button) findViewById(R.id.send_message_btn);
        mNickNameText = (TextView) findViewById(R.id.nickname);
        mPersonSignatureText = (TextView) findViewById(R.id.person_signature);
        mVideoList = (NoScrollGridView) findViewById(R.id.video_list);
        mScrollView = (MyScrollView) findViewById(R.id.anchor_detail_scroll);
        mScrollView.setOnScrollListener(this);
        mAdapter = new VideoAdapter(mContext);
        mVideoList.setAdapter(mAdapter);
        mVideoList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                VideoInfo info = (VideoInfo) mAdapter.getItem(position);
                Intent intent = new Intent(mContext, VideoDetailActivity.class);
                intent.putExtra("FEE", info.getFee());
                intent.putExtra("UID", info.getUserId());
                intent.putExtra("videoid", info.getVideoId());
                intent.putExtra("YOUKUVIDEOID", info.getPath());
                intent.putExtra("ZUOZHE", info.getUserName());
                startActivity(intent);
            }
        });

        photoGridView = (NoScrollGridView) findViewById(R.id.user_photo_list);
        photeAdapter = new PhotoAdapter(mContext,photoGridView);
        photoGridView.setAdapter(photeAdapter);

        photoGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (position < 0) return;
                PhotoInfo fdinfo = (PhotoInfo) photeAdapter.getItem(position);
                String bigImage = fdinfo.getPhotoURL();
                ArrayList<String> adlist = new ArrayList<String>();
                adlist.add(bigImage);
                Intent intent = new Intent(mContext, ShowBigImageActivity.class);
                intent.putExtra("photoList",adlist);
                intent.putExtra("currentPosition", 0);
                startActivity(intent);
            }
        });
        mGuanZhuBtn = (CheckBox) findViewById(R.id.guanzhu_btn);
        mGuanZhuBtn.setOnClickListener(this);
        mGuanZhuBtn.setChecked(true);

        mPhotoBtn = (CheckBox) findViewById(R.id.photo_btn);
        mPhotoBtn.setOnClickListener(this);
        mPhotoBtn.setChecked(false);
        //mGuanzhuLayout = (LinearLayout) findViewById(R.id.guanzhu_layout);
        mPhotoLayout = (LinearLayout) findViewById(R.id.photo_layout);
        // mGuanzhuLayout.setVisibility(View.VISIBLE);
        mPhotoLayout.setVisibility(View.GONE);




        initPopWindow();
        getUserInfo();
        chatLayout = (LinearLayout) findViewById(R.id.liaotian);
        chatLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //TODO 发消息界面
//                String Uid = userInfo.getUserId();
//                if(Uid!=null){
//                    Uid = Uid.toLowerCase();
//                }
//                String opid = userInfo.getOpenId();
//                if (opid != null) {
//                    Uid = opid.toLowerCase();
//                }
//
//                Intent intent = new Intent(mContext, ChatActivity.class);
//                intent.putExtra("userId", Uid);
//                intent.putExtra("userNick", userInfo.getNickName());
//                intent.putExtra("myLogo", EatShowApp.getInstance().getmUserInfo().getUserLogo());
//                intent.putExtra("fromLogo", userInfo.getUserLogo());
//                mContext.startActivity(intent);
                if(getEatShowApp().getmUserInfo()!= null) {
                    //TODO 发消息界面
                    String Uid = userInfo.getUserId().toLowerCase();
                    String opid = userInfo.getOpenId();
                    if (opid != null) {
                        Uid = opid.toLowerCase();
                    }

                    Intent intent = new Intent(mContext, ChatActivity.class);
                    intent.putExtra("userId", Uid);
                    intent.putExtra("userNick", userInfo.getNickName());
                    intent.putExtra("myLogo", EatShowApp.getInstance().getmUserInfo().getUserLogo());
                    intent.putExtra("fromLogo", userInfo.getUserLogo());
                    mContext.startActivity(intent);
                }else{
                    Intent lintent = new Intent(mContext, LoginActivity.class);
                    mContext.startActivity(lintent);
                }
            }
        });

        toupiaoLayout = (LinearLayout) findViewById(R.id.toupiao);
        toupiaoLayout.setOnClickListener(this);
        share = (ImageView) findViewById(R.id.zhubo_share);
        share.setOnClickListener(this);
    }

    private void initPopWindow() {
        View view = LayoutInflater.from(mContext).inflate(R.layout.share_pop,
                null);
        ((ImageView) view.findViewById(R.id.share_to_timeline))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weixinfriend))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_weibo))
                .setOnClickListener(this);
        ((ImageView) view.findViewById(R.id.share_to_qq))
                .setOnClickListener(this);
        popWindow = new PopupWindow(view, ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        popWindow.setBackgroundDrawable(new ColorDrawable());
        popWindow.setFocusable(true);
        popWindow.setOutsideTouchable(true);
    }

    private void getUserInfo() {
        GetUserInfoTask task = new GetUserInfoTask(mUserId);
        task.addListener(mAnchorInfoListener);
        mUserTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void getMyPhotos(){
        if (currentPage_p == 0) {
           // Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            noMoreText.setVisibility(View.VISIBLE);
            return;
        }
        if (xiangceListTaskId != -1) {
            return;
        }
        ChaKanXiangCeTask task = new ChaKanXiangCeTask(size,currentPage_p,mUserId);
        task.addListener(mAnchorInfoListener);
        xiangceListTaskId = getEatShowApp().getTaskManager().addTask(task);
    }

    private void getVideoList() {

        if (currentPage == 0) {
//            Toast.makeText(mContext, R.string.no_more, Toast.LENGTH_SHORT).show();
            noMoreText.setVisibility(View.VISIBLE);
            return;
        }
        if (mVideoListTaskId != -1) {
            return;
        }
        GetOtherVideoListTask videoListTask = new GetOtherVideoListTask(size, currentPage, mUserId);
        videoListTask.addListener(mAnchorInfoListener);
        mVideoListTaskId = getEatShowApp().getTaskManager().addTask(videoListTask);
    }

    private TaskEventListener mAnchorInfoListener = new ShowToastTaskEventListener(this) {
        @Override
        public void handleTaskCompleted(int taskId, int result, Object data) {
            super.handleTaskCompleted(taskId, result, data);
            if (taskId == mUserTaskId) {
                mUserTaskId = -1;
                if (data != null) {
                    userInfo = (EatShowUserInfo) data;
                    updateUserInfo();
                    if (userInfo.getUserType() ==1) {
                        currentPage = 1;
                        getVideoList();
                    }
                }
            } else if (taskId == mVideoListTaskId) {
                mVideoListTaskId = -1;
                if (currentPage == 1) {
                    mAdapter.clearData();
                    noMoreText.setVisibility(View.GONE);
                }
                List<VideoInfo> videoInfoList = new ArrayList<VideoInfo>();
                if (data != null) {
                    videoInfoList = (List<VideoInfo>) data;

                }

                if (videoInfoList != null && videoInfoList.size() > 0) {
                    mAdapter.updateData(videoInfoList);
                  //  mHisZuoPin.setText(mContext.getString(R.string.tadezuopin) + "   (" + videoInfoList.size() + "个" + ")");
                }
                if (currentPage == 1) {
                    attentionBtn.setFocusable(true);
                    attentionBtn.setFocusableInTouchMode(true);
                    attentionBtn.requestFocus();
                }
                currentPage = result;

            } else if (taskId == cancleFocusTaskId) {
                userInfo.setIsFocus(true);
                attentionBtn.setText(R.string.attention);
                attentionBtn.setTextColor(getResources().getColor(R.color.red));
                userInfo.setFansNum(String.valueOf((Integer.valueOf(userInfo.getFansNum()) - 1)));
                fansNumText.setText("粉丝" + "    " + userInfo.getFansNum());
            } else if (taskId == focusTaskId) {
                userInfo.setIsFocus(false);
                attentionBtn.setText(R.string.attention_already);
                attentionBtn.setTextColor(getResources().getColor(R.color.detail_gray));
                userInfo.setFansNum(String.valueOf((Integer.valueOf(userInfo.getFansNum()) + 1)));
                fansNumText.setText("粉丝" + "    " + userInfo.getFansNum());
            } else if (taskId == tpTaskId) {

                ToastUtil.showMessage(mContext, "投票成功");
            }else if(taskId == xiangceListTaskId){
                xiangceListTaskId = -1;
                if (data != null){
                    List<PhotoInfo> list = (List<PhotoInfo>) data;
                    if (currentPage_p ==1){
                        photeAdapter.clearData();
                        noMoreText.setVisibility(View.GONE);
                    }
                    photeAdapter.updateData(list);
                    // photoGridView.onRefreshComplete();
                    currentPage_p = result;

                }
            }
        }

        @Override
        public void handleTaskError(int taskId, int errorCode, String errorMsg) {
            super.handleTaskError(taskId, errorCode, errorMsg);
        }

        @Override
        public void handleTaskMessage(int taskId, Object data) {
            super.handleTaskMessage(taskId, data);
        }
    };

    private void updateUserInfo() {
        if (userInfo != null) {
            String headImgUrl = userInfo.getUserLogo();
            if (headImgUrl != null && headImgUrl.length() > 0) {
                ImageCache.getInstance(mContext).loadBitmapToView(mHeadImg, headImgUrl, ViewUtil.getHeadImageSize(mContext));
            }
            if (userInfo.getUserType() == 1) {
                attentionBtn.setVisibility(View.VISIBLE);
//                sendMsgBtn.setVisibility(View.GONE);
                fansNumText.setVisibility(View.VISIBLE);
                fansNumText.setText("粉丝" + "    " + userInfo.getFansNum());
                if (!userInfo.isFocus()) {
                    attentionBtn.setText(R.string.attention_already);
                    attentionBtn.setTextColor(getResources().getColor(R.color.detail_gray));
                } else {
                    attentionBtn.setText(R.string.attention);
                    attentionBtn.setTextColor(getResources().getColor(R.color.red));
                }
            } else {
                attentionBtn.setVisibility(View.GONE);
//                sendMsgBtn.setVisibility(View.VISIBLE);
                fansNumText.setVisibility(View.GONE);
            }
            if (userInfo.getNickName() != null) {
                try {
                    mNickNameText.setText(URLDecoder.decode(userInfo.getNickName(), "utf-8"));
                    share_title = URLDecoder.decode(userInfo.getNickName(),"utf-8") + "的直播秀，速来围观！";
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }
            if (userInfo.getUserSign() != null) {
                try {
                    mPersonSignatureText.setText(URLDecoder.decode(userInfo.getUserSign(), "utf-8"));
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
            }


        }
    }


    @Override
    public void onScroll() {


        if (mVideoList.getVisibility() == View.VISIBLE) {

            getVideoList();
        } else if (photoGridView.getVisibility() == View.VISIBLE) {

            getMyPhotos();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.attention_btn:
                if (!userInfo.isFocus()) {
                    AddOrCancleFocusTask task = new AddOrCancleFocusTask(mUserId,"1");
                    task.addListener(mAnchorInfoListener);
                    cancleFocusTaskId = getEatShowApp().getTaskManager().addTask(task);
                } else {
                    AddOrCancleFocusTask task = new AddOrCancleFocusTask(mUserId,"0");
                    task.addListener(mAnchorInfoListener);
                    focusTaskId = getEatShowApp().getTaskManager().addTask(task);
                }
                break;
            case R.id.toupiao:
                TouPiaoTask tpTask = new TouPiaoTask(mUserId, "");
                tpTask.addListener(mAnchorInfoListener);
                tpTaskId = getEatShowApp().getTaskManager().addTask(tpTask);
                break;
            case R.id.zhubo_share:
                popWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
                break;
            case R.id.share_to_timeline:
                weixinsharetype = "sharefriends";
                //PalLog.e("url",share_path);
                shareToWeiXin(share_path, true);
                popWindow.dismiss();
                break;
            case R.id.share_to_weixinfriend:
                weixinsharetype = "sharefriend";
               // PalLog.e("url",share_path);
                shareToWeiXin(share_path, false);
                popWindow.dismiss();
                break;
            case R.id.share_to_weibo:
                shareToWeiBo(share_path);
                popWindow.dismiss();
                break;
            case R.id.share_to_qq:

                final Bundle params = new Bundle();
                params.putInt(QQShare.SHARE_TO_QQ_KEY_TYPE, QQShare.SHARE_TO_QQ_TYPE_DEFAULT);
                params.putString(QQShare.SHARE_TO_QQ_TITLE, "第一课堂");
                params.putString(QQShare.SHARE_TO_QQ_SUMMARY, share_title);
                params.putString(QQShare.SHARE_TO_QQ_TARGET_URL, share_path);
                params.putString(QQShare.SHARE_TO_QQ_IMAGE_URL, "http://www.chiboker.com:8096/liveshow/images/app_icon.png");
                // params.putByteArray(QQShare.SHARE_TO_QQ_IMAGE_URL,weixinshareByte);
                params.putString(QQShare.SHARE_TO_QQ_APP_NAME, "第一课堂");
                mTencent.shareToQQ(this, params, qqShareListener);
                popWindow.dismiss();
                break;
            case R.id.fans_num:
                Intent moreIntent = new Intent(mContext,FansListActivity.class);
                moreIntent.putExtra("UserId", mUserId);
                startActivity(moreIntent);
                break;

            case R.id.guanzhu_btn:
                mGuanZhuBtn.setChecked(true);
                mPhotoBtn.setChecked(false);
                mPhotoLayout.setVisibility(View.GONE);
                mVideoList.setVisibility(View.VISIBLE);
                if(mAdapter!=null&&mAdapter.getCount()==0){
                    getVideoList();
                }
                break;
            case R.id.photo_btn:
                mPhotoBtn.setChecked(true);
                mGuanZhuBtn.setChecked(false);
                mPhotoLayout.setVisibility(View.VISIBLE);
//                    List<PhotoInfo> photoList = new ArrayList<PhotoInfo>();
//                    photeAdapter.updateData(photoList);
                mVideoList.setVisibility(View.GONE);
                if(photeAdapter!=null&&photeAdapter.getCount()==0){
                    getMyPhotos();
                }
                break;

        }
    }


    IUiListener qqShareListener = new IUiListener() {
        @Override
        public void onCancel() {

        }

        @Override
        public void onComplete(Object response) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onError(UiError e) {
            // TODO Auto-generated method stub

        }
    };


    class WeixinShareReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            System.out.println(intent.getAction());
            weixinuseropenid = intent.getStringExtra(ProtocolConst.WEIXIN_OPENID);
            // doShareWeiXinQuanGetPoint();
            if (intent.getAction().equalsIgnoreCase(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION)){

            }else if (intent.getAction().equalsIgnoreCase(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION)){

            }

            if (mWeixinShareReceive != null) {
                unregisterReceiver(mWeixinShareReceive);
                mWeixinShareReceive = null;
            }
        }

    }


    private void shareToWeiXin(String shareUrl, boolean isTimeLine) {
        if (!api.isWXAppSupportAPI() || !api.isWXAppInstalled()) {
            Toast.makeText(mContext, R.string.need_weixin_app, Toast.LENGTH_SHORT).show();
            return;
        }

        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }
        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WXEntryActivity.WEIXIN_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
        WXWebpageObject webPage = new WXWebpageObject();
        webPage.webpageUrl = shareUrl;
        WXMediaMessage msg = new WXMediaMessage(webPage);
        //msg.title = ppntitle;
        if (isTimeLine){
            msg.title = share_title;
        }else {
            msg.title = "第一课堂";
        }
        msg.description = share_title;
        Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.app_icon);
        weixinshareByte = WeixinShareUtil.bmpToByteArray(bmp, true);
        if (weixinshareByte != null && weixinshareByte.length != 0) {
            msg.thumbData = weixinshareByte;
        }
        SendMessageToWX.Req req = new SendMessageToWX.Req();
        req.transaction = buildTransaction("webpage");
        req.message = msg;
        req.scene = isTimeLine ? SendMessageToWX.Req.WXSceneTimeline
                : SendMessageToWX.Req.WXSceneSession;
        api.sendReq(req);
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis())
                : type + System.currentTimeMillis();
    }


    private void shareToWeiBo(String webpage) {

        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }

        if (mWeixinShareReceive == null) {
            mWeixinShareReceive = new WeixinShareReceive();
            IntentFilter filter = new IntentFilter();
            filter.addAction(WbcallbackActivity.WEIBO_SHARE_SUCCESS_ACTION);
            registerReceiver(mWeixinShareReceive, filter);
        }
//		if (mWeiboShareAPI.isWeiboAppSupportAPI()) {
//        WeiboMultiMessage weiboMessage = new WeiboMultiMessage();
        // if (hasText) {
        // weiboMessage.mediaObject = getTextObj();
        // }
        // if (hasImage) {
        // weiboMessage.mediaObject = getImageObj();
        // }
//        if (!TextUtils.isEmpty(webpage)) {
//            TextObject textobject = new TextObject();
//            textobject.text = "第一课堂";
////            weiboMessage.textObject = textobject;
//            WebpageObject mediaObject = new WebpageObject();
//            mediaObject.identify = Utility.generateGUID();
//            mediaObject.defaultText = "第一课堂";
//            mediaObject.title = "第一课堂";
//            mediaObject.description = share_title;
//            mediaObject.actionUrl = webpage;
//            if (weiboShareBitmap != null) {
//                mediaObject.setThumbImage(weiboShareBitmap);
//            } else {
//                mediaObject.setThumbImage(BitmapFactory.decodeResource(
//                        getResources(), R.drawable.app_icon));
//            }
//            weiboMessage.mediaObject = mediaObject;
//        }
        // if (hasMusic) {
        // weiboMessage.mediaObject = getMusicObj();
        // }
        // if (hasVideo) {
        // weiboMessage.mediaObject = getVideoObj();
        // }
            /*
			 * if (hasVoice) { weiboMessage.mediaObject = getVoiceObj(); }
			 */

//        // 2. 初始化从第三方到微博的消息请求
//        SendMultiMessageToWeiboRequest request = new SendMultiMessageToWeiboRequest();
//        // 用transaction唯一标识一个请求
//        request.transaction = String.valueOf(System.currentTimeMillis());
//        request.multiMessage = weiboMessage;
//
//        // 3. 发送请求消息到微博，唤起微博分享界面
//        AuthInfo authInfo = new AuthInfo(this, ProtocolConst.WEIBO_APP_KEY, ProtocolConst.WEIBO_REDIRECT_URL, ProtocolConst.WEIBO_SCOPE);
//        Oauth2AccessToken accessToken = AccessTokenKeeper.readAccessToken(getApplicationContext());
//        String token = "";
//        if (accessToken != null) {
//            token = accessToken.getToken();
//            weibouserid = accessToken.getUid();
//           // PalLog.e("旧token", weibouserid);
//        }
//        mWeiboShareAPI.sendRequest(this, request, authInfo, token, new WeiboAuthListener() {
//
//
//            @Override
//            public void onWeiboException(WeiboException arg0) {
//            }
//
//            @Override
//            public void onComplete(Bundle bundle) {
//                Oauth2AccessToken newToken = Oauth2AccessToken.parseAccessToken(bundle);
//                AccessTokenKeeper.writeAccessToken(getApplicationContext(), newToken);
//
//                weibouserid = newToken.getUid();
//               // PalLog.e("新token", weibouserid);
////                    Toast.makeText(getApplicationContext(), "UID = "+weiboOpenId+"onAuthorizeComplete token = " + newToken.getToken(), 0).show();
//            }
//
//            @Override
//            public void onCancel() {
//            }
//        });
//
//
    }


    @Override
    public void onResponse(BaseResponse arg0) {

        switch (arg0.errCode) {
            case WBConstants.ErrorCode.ERR_OK:
                Toast.makeText(this, R.string.weibosdk_toast_share_success,
                        Toast.LENGTH_LONG).show();
                //doShareWeiboGetPoint();
                break;
            case WBConstants.ErrorCode.ERR_CANCEL:
                Toast.makeText(this, R.string.weibosdk_toast_share_canceled,
                        Toast.LENGTH_LONG).show();
                break;
            case WBConstants.ErrorCode.ERR_FAIL:
                Toast.makeText(
                        this,
                        getString(R.string.weibosdk_toast_share_failed)
                                + "Error Message: " + arg0.errMsg,
                        Toast.LENGTH_LONG).show();
                break;
        }


    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mWeixinShareReceive != null){
            unregisterReceiver(mWeixinShareReceive);
            mWeixinShareReceive = null;
        }
    }
}
